package com.parking.mgr.useraccount.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.parking.mgr.common.constant.CommonConstant;
import com.parking.mgr.common.enums.CommonStatusEnum;
import com.parking.mgr.common.exception.ServiceException;
import com.parking.mgr.common.exception.enums.CommonExceptionEnum;
import com.parking.mgr.common.exception.enums.DeleteUpdateExceptionEnums;
import com.parking.mgr.common.factory.PageFactory;
import com.parking.mgr.common.util.IdUtils;
import com.parking.mgr.useraccount.facede.BasicRoleServiceFacede;
import com.parking.mgr.useraccount.facede.LoginServiceFacede;
import com.parking.mgr.useraccount.model.entity.BasicRoleEntity;
import com.parking.mgr.useraccount.model.entity.LoginTokenEntity;
import com.parking.mgr.useraccount.model.mapper.BasicRoleMapper;
import com.parking.mgr.useraccount.model.mapstruct.BasicRoleMapStruct;
import com.parking.mgr.useraccount.model.param.BasicRoleParam;
import com.parking.mgr.useraccount.model.vo.BasicRoleVO;
import com.parking.mgr.useraccount.service.BasicRoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Collection;

/**
 * @author shilintao
 * @ClassName BasicRoleServiceImpl
 * @Description TODO
 * @Date 2023/5/23
 */
@Service
public class BasicRoleServiceImpl extends ServiceImpl<BasicRoleMapper, BasicRoleEntity> implements BasicRoleService {

    @Resource
    private BasicRoleMapper basicRoleMapper;

    @Resource
    private BasicRoleMapStruct basicRoleMapStruct;

    @Resource
    private LoginServiceFacede loginServiceFacede;

    @Resource
    private BasicRoleServiceFacede basicRoleServiceFacede;

    @Override
    public IPage<BasicRoleVO> list(BasicRoleParam basicRoleParam) {
        LambdaQueryWrapper<BasicRoleEntity> queryWrapper = new LambdaQueryWrapper<>();
        if (ObjectUtil.isNotNull(basicRoleParam)) {
//            // 根据菜单名称迷糊查询
//            if(ObjectUtil.isNotNull(basicRoleParam.getFName())){
//                queryWrapper.like(BasicRoleEntity::getFName,basicRoleParam.getFName());
//            }

        }
//        queryWrapper.eq(BasicRoleEntity::getFKey,basicRoleParam.getFKey());
//        queryWrapper.eq(BasicRoleEntity::getFEnableState,CommonStatusEnum.ENABLE.getCode());
        // 根据排序升序排序，序号越小越在前
        queryWrapper.orderByAsc(BasicRoleEntity::getFSortNumber);
        queryWrapper.orderByAsc(BasicRoleEntity::getFInsertTimeMillis);

        Page<BasicRoleEntity> page = PageFactory.defaultPage(basicRoleParam.getPageSize(), basicRoleParam.getCurrPage());
        IPage<BasicRoleVO> rolePageVO = basicRoleMapStruct.entity2VO(this.page(page, queryWrapper));
        return rolePageVO;
    }

    @Override
    public IPage<BasicRoleVO> listEnable(BasicRoleParam basicRoleParam) {
        LambdaQueryWrapper<BasicRoleEntity> queryWrapper = new LambdaQueryWrapper<>();
        if (ObjectUtil.isNotNull(basicRoleParam)) {
//            // 根据菜单名称迷糊查询
//            if(ObjectUtil.isNotNull(basicRoleParam.getFName())){
//                queryWrapper.like(BasicRoleEntity::getFName,basicRoleParam.getFName());
//            }


        }
//        queryWrapper.eq(BasicRoleEntity::getFKey,basicRoleParam.getFKey());
        queryWrapper.eq(BasicRoleEntity::getFEnableState, CommonStatusEnum.ENABLE.getCode());
        // 根据排序升序排序，序号越小越在前
        queryWrapper.orderByAsc(BasicRoleEntity::getFSortNumber);
        queryWrapper.orderByAsc(BasicRoleEntity::getFInsertTimeMillis);

        Page<BasicRoleEntity> page = PageFactory.defaultPage(basicRoleParam.getPageSize(), basicRoleParam.getCurrPage());
        IPage<BasicRoleVO> rolePageVO = basicRoleMapStruct.entity2VO(this.page(page, queryWrapper));
        return rolePageVO;
    }

    @Override
    public void add(BasicRoleParam basicRoleParam) {
        BasicRoleEntity basicRoleEntity = new BasicRoleEntity();
        BeanUtil.copyProperties(basicRoleParam, basicRoleEntity);
        //String fKeyParam = basicRoleParam.getFKey();
        // UUID生成fKey
        String fKey = IdUtils.getKeyUUID();
        //设置启用状态
        basicRoleEntity.setFEnableState(CommonStatusEnum.ENABLE.getCode());
        basicRoleEntity.setId(IdUtils.getId());
        this.save(basicRoleEntity);

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(Collection<String> ids) {

        for (String id : ids) {
            BasicRoleEntity basicRoleEntity = this.basicRoleMapper.selectById(id);
            if (ObjectUtil.isNull(basicRoleEntity)) {
                throw new ServiceException(CommonExceptionEnum.DATA_NOT_EXIST.getMessage());

            }
            if (ObjectUtil.equals(CommonConstant.CAN_DELETE, basicRoleEntity.getFCanDelete())) {
                this.removeById(id);
            } else {
                throw new ServiceException(DeleteUpdateExceptionEnums.CAN_NOT_DELETE.getMessage());
            }
        }
//        this.removeByIds(ids);
        /*String id = basicRoleParam.getId();
        BasicRoleEntity basicRoleEntity = new BasicRoleEntity();
        LambdaQueryWrapper<BasicRoleEntity> basicRoleEntityLambdaQueryWrapper =
                new LambdaQueryWrapper<BasicRoleEntity>().in(BasicRoleEntity::getId,id);
        basicRoleMapper.delete(basicRoleEntityLambdaQueryWrapper);*/
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(BasicRoleParam basicRoleParam) {
        BasicRoleEntity basicRoleEntity = this.basicRoleMapper.selectById(basicRoleParam.getId());
        if (ObjectUtil.isNull(basicRoleEntity)) {
            throw new ServiceException(CommonExceptionEnum.DATA_NOT_EXIST.getMessage());

        }
        // 修改的角色旧数据
//        BasicRoleEntity currentRole = this.queryBasicRole(basicRoleParam);
        if (ObjectUtil.equals(CommonConstant.CAN_UPDATE, basicRoleEntity.getFCanUpdate())) {
            BeanUtil.copyProperties(basicRoleParam, basicRoleEntity);
            basicRoleMapper.updateById(basicRoleEntity);
        } else {
            throw new ServiceException(DeleteUpdateExceptionEnums.CAN_NOT_UPDATE.getMessage());
        }
    }


    @Override
    public void move(String currentId, String currentGroupId, String newGroupId) {
        // 获取当前角色对象
        BasicRoleEntity currentRole = this.getById(currentId);
        //获取目标角色组ID

        this.updateById(currentRole);
    }

    @Override
    public String getRoleIdByName(String roleName) {
        LambdaQueryWrapper<BasicRoleEntity> queryWrapper = new LambdaQueryWrapper<BasicRoleEntity>()
                .eq(BasicRoleEntity::getFName, roleName);

        BasicRoleEntity basicRoleEntity = this.getOne(queryWrapper);
        if (ObjectUtil.isNotNull(basicRoleEntity)) {
            return basicRoleEntity.getId();
        } else {
            return "";
        }
    }

    @Override
    public BasicRoleEntity getBasicRoleById(String id) {

        return this.getById(id);
    }

    @Override
    public BasicRoleEntity getOneByRequest(HttpServletRequest request) {

        String loginToken = request.getHeader(CommonConstant.LOGIN_TOKEN);
        String clientId = request.getHeader(CommonConstant.CLIENT_ID);

        LoginTokenEntity loginTokenEntity = loginServiceFacede.getLoginTokenEntity(loginToken, clientId);
        if (ObjectUtil.isNull(loginTokenEntity)) {
            throw new ServiceException("无登录用户");
        }

        String userPassportId = loginTokenEntity.getFkUserPassportId();
        String roleId = basicRoleServiceFacede.getOneByPassportId(userPassportId);
        return basicRoleServiceFacede.getBasicRoleById(roleId);
    }


    private String isEnableOperation(String id) {
        BasicRoleEntity basicRoleEntity = basicRoleMapper.selectById(id);
        String returnStr = "1";
        String canDelete = basicRoleEntity.getFCanDelete();
        if (StrUtil.equals("1", canDelete)) {
            return returnStr;
        } else {
            throw new ServiceException(DeleteUpdateExceptionEnums.CAN_NOT_DELETE.getMessage());
        }

    }

    /**
     * 获取角色数据
     *
     * @param basicRoleParam
     * @return
     */
    private BasicRoleEntity queryBasicRole(BasicRoleParam basicRoleParam) {
        BasicRoleEntity basicRoleEntity = this.getById(basicRoleParam.getId());
        if (ObjectUtil.isNull(basicRoleEntity)) {
            throw new ServiceException(CommonExceptionEnum.DATA_NOT_EXIST.getMessage());
        }
        return basicRoleEntity;
    }
}
